package com.ysdz.tibetan.tibetanmini.order.service.impl;

import com.ysdz.tibetan.tibetanmini.order.beans.Orders;
import com.ysdz.tibetan.tibetanmini.order.dao.OrdersMapper;
import com.ysdz.tibetan.tibetanmini.order.service.OrderService;
import com.ysdz.tibetan.tibetanmini.security.beans.ConsumerDetails;
import com.ysdz.tibetan.tibetanmini.utils.JWTTokenUtils;
import com.ysdz.tibetan.tibetanminicommons.common.ReturnMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ReturnMsg insertOrder(Orders orders) {
        // 拿到请求头
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authorization = request.getHeader("Authorization");
        // 拿到 Token 进行解析
        ConsumerDetails consumerDetails = JWTTokenUtils.parseAccessToken(authorization);
        // 根据 userId 插入数据
        orders.setOrderId(UUID.randomUUID().toString());
        ordersMapper.insert(orders);
        return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "成功!", null);
    }

    @Override
    public ReturnMsg getAllOrders(String userId) {
        String key = "order_all";
        ValueOperations<String, List<Orders>> valueOperations = redisTemplate.opsForValue();
        boolean haskey = redisTemplate.hasKey(key);
        if(haskey){
            List<Orders> orders = valueOperations.get(key);
            return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "成功查询!", orders);
        }else{
            // 在 Mysql 中查询
            Example example = new Example(Orders.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", userId);
            List<Orders> orders = ordersMapper.selectByExample(userId);

            // 放入 Redis
            valueOperations.set(key, orders);
            return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "成功查询!", orders);
        }
    }

    @Override
    public ReturnMsg getValidOrder(String userId) {
        return null;
    }
}
